常用日期计算获某天的第一秒和最后一秒

下载地址

常用字符串处理

使用

1
2
String start = DateToStringBeginOrEnd(new Date(),true); //2020-11-05 00:00:00
String end = DateToStringBeginOrEnd(new Date(),false); //2020-11-05 23:59:59

源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
 package com.wangjikai.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

public void testTime() throws Exception {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
//c.add(Calendar.MONTH, -1); //得到前一个月
c.add(Calendar.DATE, -1); //得到前一天
String jssj = DateToStringBeginOrEnd(c.getTime(),false);

}
/**
* 获取某一天的0点0分0秒 或者 23点59分59秒
* @param date
* @param flag
* @return
*/
public String DateToStringBeginOrEnd(Date date, Boolean flag) {
String time = null;
SimpleDateFormat dateformat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar1 = Calendar.getInstance();
//获取某一天的0点0分0秒 或者 23点59分59秒
if (flag == true) {
calendar1.setTime(date);
calendar1.set(calendar1.get(Calendar.YEAR), calendar1.get(Calendar.MONTH), calendar1.get(Calendar.DAY_OF_MONTH),
0, 0, 0);
Date beginOfDate = calendar1.getTime();
time = dateformat1.format(beginOfDate);
System.out.println(time);
}else{
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date);
calendar1.set(calendar2.get(Calendar.YEAR), calendar2.get(Calendar.MONTH), calendar2.get(Calendar.DAY_OF_MONTH),
23, 59, 59);
Date endOfDate = calendar1.getTime();
time = dateformat1.format(endOfDate);
System.out.println(time);
}
return time;
}
}
继开 wechat
欢迎加我的微信,共同交流技术